﻿using System;
using System.Windows.Forms;
using WebMoney.SignerFX;
using WebMoney.WMSignerFX.KeysExtractor.Exceptions;
using WebMoney.WMSignerFX.KeysExtractor.Properties;
using WebMoney.SignerFX.Exceptions;

namespace WebMoney.WMSignerFX.KeysExtractor
{
    internal partial class IdPasswordForm : Form
    {
        private const int WMID_LEN = 12;
        private const int KEYS_DATA_LEN = 164;

        private byte[] _keysData;
        private BKeys _keys;

        internal BKeys Keys
        {
            get
            {
                return _keys;
            }
        }

        internal IdPasswordForm(byte[] keysData)
        {
            InitializeComponent();

            if (null == keysData)
                throw new ArgumentNullException("keysData");

            if (KEYS_DATA_LEN != keysData.Length)
                throw new ArgumentOutOfRangeException("keysData");

            _keysData = keysData;
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            try
            {
                Extractor extractor = new Extractor(_keysData, idTextBox.Text, pwdTextBox.Text);
                _keys = extractor.Keys;
            }
            catch (ArgumentNullException ex)
            {
                exceptionHandler(ex);
                return;
            }
            catch(ArgumentOutOfRangeException ex)
            {
                exceptionHandler(ex);
                return;
            }
            catch (KeysSizeException ex)
            {
                exceptionHandler(ex);
                return;
            }
            catch (BadKeysException ex)
            {
                exceptionHandler(ex);
                return;
            }

            if (null == _keys)
                throw new UnexpectedException("_base64 is null or empty");

            DialogResult = DialogResult.OK;
        }

        private void exceptionHandler(Exception ex)
        {
            string message = (string.IsNullOrEmpty(ex.Message) ? string.Empty : string.Format(null, " ({0})", ex.Message));

            MessageBox.Show(this, string.Format(null, "{0} {1}", Resources.WrongData, message), Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void idTextBox_TextChanged(object sender, EventArgs e)
        {
            checkText();
        }

        private void pwdTextBox_TextChanged(object sender, EventArgs e)
        {
            checkText();
        }

        private void checkText()
        {
            if (WMID_LEN == idTextBox.Text.Length)
                pwdTextBox.Enabled = true;
            else
                pwdTextBox.Enabled = false;

            if (pwdTextBox.Enabled && pwdTextBox.Text.Length > 0)
                okButton.Enabled = true;
            else
                okButton.Enabled = false;
        }
    }
}